package com.javaee.web.servlet;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.javaee.ejb.entity.Activity;
import com.javaee.ejb.entity.Project;
import com.javaee.ejb.session.remote.ActivityManagerRemote;
import com.javaee.ejb.session.remote.ProjectManagerRemote;
import com.javaee.web.HttpServletBase;
import com.javaee.web.SiteParameters;

/**
 * Servlet implementation class AddActivityServlet
 */
public class AddActivityServlet extends HttpServletBase {
	private static final long serialVersionUID = 1L;

	@EJB
	private ProjectManagerRemote projectManager;

	@EJB
	private ActivityManagerRemote activityManager;

	/**
	 * @see HttpServletBase#HttpServletBase()
	 */
	public AddActivityServlet() {
		super();
	}

	@Override
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int projectId = Integer.parseInt(request.getParameter("projectId"));
		int time = 0;
		Date date = null;
		String description = null;
		Project project = null;
		Activity activity = null;

		HashMap<String, Boolean> hashInvalid = new HashMap<String, Boolean>();
		HashMap<String, String> hashValue = new HashMap<String, String>();

		hashValue.put("projectId", request.getParameter("projectId"));
		hashValue.put("time", request.getParameter("time"));
		hashValue.put("date", request.getParameter("date"));
		hashValue.put("description", request.getParameter("description"));

		// Verification des valeurs transmises
		try {
			time = Integer.parseInt(request.getParameter("time"));
		} catch (Exception e) {
			hashInvalid.put("time", new Boolean(false));
		}

		try {
			date = new SimpleDateFormat("dd/MM/yyyy").parse(request
					.getParameter("date"));
		} catch (Exception e) {
			hashInvalid.put("date", new Boolean(false));
		}

		if (hashInvalid.isEmpty() == false) {
			// Le formulaire est invalide
			request.setAttribute("hashInvalid", hashInvalid);
			request.setAttribute("hashValue", hashValue);

			loadJSP(SiteParameters.getServletPath("activity"), request,
					response);
			return;
		} else {
			description = request.getParameter("description");

			// Recuperation du projet selectionne
			project = projectManager.getById(projectId);

			// Creation de l'activite
			activity = new Activity();
			activity.setCollaborator(currentEmployee);
			activity.setDay(date);
			activity.setDescription(description);
			activity.setIsValid(true);
			activity.setProject(project);
			activity.setTimeSpent(time);

			// Sauvegarde de l'activite
			activityManager.saveActivity(activity);

			// Redirection vers le dashboard
			response.sendRedirect(SiteParameters.getFullServletPath("project")
					+ "?projectId=" + projectId);
		}
	}
}
